/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MainZhiShiActivity.java   
 * @Package com.jiyi.activity.main   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-23 上午10:02:35   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.MultiItemTypeAdapter;
import com.jiyi.adapter.recyclerview.base.ItemViewDelegate;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.maintenance.RepairTask;
import com.jiyi.bean.maintenance.RepairTask.RepairTaskItem;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.RepairTaskListEvent;
import com.jiyi.inteface.OnRcvScrollListener;
import com.jiyi.inteface.WebApi;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DialogTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: MainZhiShiActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-23 上午10:02:35
 * 
 */
public class AllRepairTaskFragment extends Fragment implements
		OnRefreshListener {

	LayoutInflater inflater;
	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	EmptyWrapper adapter;
	ViewGroup container;
	int type;
	private List<RepairTask> dataList = new ArrayList<RepairTask>();
	Dialog dialog;

	// 是否刷新模式
	boolean isRefresh = false;
	int pageNo = 1;// 页码
	private final int LOAD_DATA = 5; // 加载数据事件
	private boolean loadfinish = true; // 指示数据是否加载完成

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_all_wx_task, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		this.container = container;
		init();
		return view;
	}

	private void init() {
		getIntentData();
		setAdapter();
		getData();
		EventBus.getDefault().register(this);
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-8-30
	 */
	private void getIntentData() {
		type = getArguments().getInt("type", 0);
	}

	@Subscribe
	public void onRepairTaskListEvent(RepairTaskListEvent repairTaskListEvent) {
		int position = repairTaskListEvent.position;
		int childPosition = repairTaskListEvent.childPosition;
		int func = repairTaskListEvent.func;
		int recType = repairTaskListEvent.type;
		switch (recType) {
		case 0:
			// 全部的列表
			switch (func) {
			case 1:
				// 完成一个故障报表的填写
				dataList.get(position).setItemStatus(3);
				// dataList.get(position).setGetInfo(repairTaskListEvent.malfunctionItems);
				dataList.get(position).getGetInfo().get(childPosition)
						.setIs_upload("1");
				dataList.get(position).getGetInfo().get(childPosition)
						.setId(repairTaskListEvent.repairTaskItem.getId());
				adapter.notifyItemChanged(position);
				break;
			case 2:
				// 新增一个临检报告
				dataList.get(position).setItemStatus(1);
				RepairTaskItem temp = repairTaskListEvent.repairTaskItem;
				dataList.get(position).getGetInfo()
						.add(dataList.get(position).getGetInfo().size(), temp);
				adapter.notifyItemChanged(position);
				break;
			case 3:
			case 4:
				// 完成一个任务 更新状态
				dataList.get(position).setMaintenance_status(2);
				dataList.get(position).setComments(repairTaskListEvent.remark);
				adapter.notifyItemChanged(position);
				break;
			default:
				break;
			}
			break;
		case 1:
			// 待维修的列表
			switch (func) {
			case 1:
				// 完成一个故障报表的填写
				dataList.get(position).setItemStatus(3);
				// dataList.get(position).setGetInfo(repairTaskListEvent.malfunctionItems);
				dataList.get(position).getGetInfo().get(childPosition)
						.setIs_upload("1");
				adapter.notifyItemChanged(position);
				break;
			case 2:
				// 新增一个临检报告
				dataList.get(position).setItemStatus(1);
				RepairTaskItem temp = repairTaskListEvent.repairTaskItem;
				dataList.get(position).getGetInfo()
						.add(dataList.get(position).getGetInfo().size(), temp);
				adapter.notifyItemChanged(position);
				break;
			case 3:
			case 4:
				// 完成一个任务
				dataList.remove(position);
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
			break;
		case 2:

			break;

		default:
			break;
		}
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(getContext()));
		mListView.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));

		MultiItemTypeAdapter multiItemTypeAdapter = new MultiItemTypeAdapter(
				getContext(), dataList);
		multiItemTypeAdapter.addItemViewDelegate(new RepairDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new FinishDelagate());

		adapter = new EmptyWrapper(multiItemTypeAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				container, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		mListView.addOnScrollListener(new OnRcvScrollListener(){  
            @Override  
            public void onBottom() {  
                super.onBottom();  
                if (loadfinish) {
                	Log.e("加载到底部 pageNo = ", pageNo+"");
                	Log.e("加载到底部 list size = ", dataList.size()+"");
                	loadMore();
				}
                
            }  
        });  
	}

	public class RepairDelagate implements ItemViewDelegate<RepairTask> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_repair_mytask_wait;
		}

		@Override
		public boolean isForViewType(RepairTask item, int position) {
			return item.getMaintenance_status() != 2;
		}

		@Override
		public void convert(final ViewHolder holder, final RepairTask task,
				final int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvDate, task.getExpect_date());
			holder.setText(R.id.tvLeader, task.getPayout_user());
			holder.setText(R.id.tvRemark, task.getComments());

			holder.setOnClickListener(R.id.tvWriteReport,
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent intent = new Intent(v.getContext(),
									TempReportWriteActivity.class);
							intent.putExtra("id", task.getId());
							intent.putExtra("companyId", task.getCompany_id());
							intent.putExtra("type", type);
							intent.putExtra("position", position);

							startActivity(intent);
						}
					});

			if (task.getTemp_inspection() == 0) {
				if (task.getItemStatus() != 3) {
					boolean isFinish = true;
					if (task.getGetInfo() != null
							&& task.getGetInfo().size() > 0) {
						for (int i = 0; i < task.getGetInfo().size(); i++) {
							if (task.getGetInfo().get(i).getIs_upload()
									.equals("0")) {
								isFinish = false;
								break;
							}
						}
						if (isFinish) {
							task.setItemStatus(3);
						} else {
							task.setItemStatus(2);
						}
					} else {
						task.setItemStatus(2);
					}

				}
			} else {
				task.setItemStatus(0);
				if (task.getGetInfo() != null && task.getGetInfo().size() > 0) {
					task.setItemStatus(1);
					LinearLayout llReportItem = holder
							.getView(R.id.llReportItem);
					llReportItem.removeAllViews();
					for (int i = 0; i < task.getGetInfo().size(); i++) {
						final int fI = i;
						View child = inflater.inflate(
								R.layout.item_temp_report, llReportItem, false);
						TextView tvReportName = (TextView) child
								.findViewById(R.id.tvReportName);
						tvReportName.setText((fI + 1) + "");
						TextView tvRead = (TextView) child
								.findViewById(R.id.tvRead);
						tvRead.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent intent = new Intent(v.getContext(),
										TempReportReadActivity.class);
								intent.putExtra("bdid",
										task.getGetInfo().get(fI).getId());
								intent.putExtra("index", (fI + 1));
								startActivity(intent);
							}
						});
						llReportItem.addView(child);
					}
				} else {
					task.setItemStatus(0);
					LinearLayout llReportItem = holder
							.getView(R.id.llReportItem);
					llReportItem.removeAllViews();
				}
			}

			switch (task.getItemStatus()) {
			case 1:
				// 有填写过临检报表
				holder.setText(R.id.tvWriteReport, "继续填写报表");
				holder.setVisible(R.id.llReportItem, true);
				holder.setVisible(R.id.llReportFinish, true);
				holder.setVisible(R.id.llOwnerCheck, true);
				// holder.setVisible(R.id.tvFinish, true);
				RadioGroup rgCheck = holder.getView(R.id.rgCheck);
				rgCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						if (checkedId == R.id.rbNeedCheck) {
							task.setCheckStatus(0);
						} else {
							task.setCheckStatus(1);
						}
					}
				});
				holder.setOnClickListener(R.id.tvPost, new OnClickListener() {

					@Override
					public void onClick(View v) {
						doFinish(task.getId(), ((EditText) holder
								.getView(R.id.etRemark)).getText().toString(),
								task.getCheckStatus(), position, type);
					}
				});
				break;
			case 2:
				// 显示非临检的故障
				holder.setText(R.id.tvWriteReport, "开始检测维修");
				holder.setVisible(R.id.llReportFinish, false);
				holder.setOnClickListener(R.id.tvWriteReport,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								dataList.get(position).setItemStatus(3);
								adapter.notifyItemChanged(position);
							}
						});
				break;
			case 3:
				// 显示故障列表
				holder.setVisible(R.id.tvWriteReport, false);
				holder.setVisible(R.id.llMalfunctionItem, true);
				holder.setVisible(R.id.llOwnerCheck, false);
				holder.setVisible(R.id.llReportFinish, true);
				holder.setVisible(R.id.llOwnerCheck, false);
				holder.setVisible(R.id.llReportItem, false);
				if (task.getGetInfo() != null) {
					holder.setMalfunctionAdapter(R.id.childListView,
							task.getGetInfo(), type, position);
					boolean isAllFinish = true;
					for (int i = 0; i < task.getGetInfo().size(); i++) {
						RepairTaskItem malfunctionItem = task.getGetInfo().get(
								i);
						if (malfunctionItem.getIs_upload().equals("0")) {
							isAllFinish = false;
							break;
						}
					}

					if (isAllFinish) {
						holder.setEnable(R.id.tvPost, true);
						holder.setOnClickListener(R.id.tvPost,
								new OnClickListener() {

									@Override
									public void onClick(View v) {
										doFinishRepair(
												task.getId(),
												((EditText) holder
														.getView(R.id.etRemark))
														.getText().toString(),
												position, type);
									}
								});
					} else {
						holder.setEnable(R.id.tvPost, false);
						holder.setOnClickListener(R.id.tvPost, null);
					}
				} else {
					holder.setVisible(R.id.llMalfunctionItem, false);
					holder.setVisible(R.id.llReportFinish, false);
				}

				holder.setOnClickListener(R.id.rlMalf, new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (v.getTag() == null) {
							holder.setVisible(R.id.childListView, true);
							v.setTag("extend");
						} else {
							holder.setVisible(R.id.childListView, false);
							v.setTag(null);
						}
					}
				});

				break;
			default:
				holder.setText(R.id.tvWriteReport, "填写临检报告");
				holder.setVisible(R.id.llReportItem, false);
				holder.setVisible(R.id.llReportFinish, false);
				holder.setVisible(R.id.tvFinish, false);
				holder.setVisible(R.id.llMalfunctionItem, false);
				holder.setVisible(R.id.llOwnerCheck, false);
				break;
			}
		}
	}

	public class FinishDelagate implements ItemViewDelegate<RepairTask> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_repair_mytask_finish;
		}

		@Override
		public boolean isForViewType(RepairTask item, int position) {
			return item.getMaintenance_status() == 2;
		}

		@Override
		public void convert(final ViewHolder holder, final RepairTask task,
				int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());

			switch (task.getTemp_inspection()) {
			case 1:
				// 临检报表
				holder.setText(R.id.tvCompany, task.getCompany_name());
				holder.setText(R.id.tvDate, task.getExpect_date());
				holder.setText(R.id.tvLeader, task.getPayout_user());
				holder.setText(R.id.tvRemark, task.getComments());
				holder.setVisible(R.id.llMalfunctionItem, false);
				holder.setVisible(R.id.llTempReportItem, true);
				if (task.getGetInfo() != null && task.getGetInfo().size() > 0) {
					holder.setTempReportAdapter(R.id.tempReportListView,
							task.getGetInfo(), type, position);
				} else {
					holder.setVisible(R.id.llTempReportItem, false);
				}
				holder.setOnClickListener(R.id.rlTempReportExtend,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								if (v.getTag() == null) {
									holder.setVisible(R.id.tempReportListView,
											true);
									v.setTag("extend");
								} else {
									holder.setVisible(R.id.tempReportListView,
											false);
									v.setTag(null);
								}
							}
						});
				break;
			default:
				// 故障
				holder.setVisible(R.id.llMalfunctionItem, true);
				holder.setVisible(R.id.llTempReportItem, false);
				holder.setVisible(R.id.childListView, false);
				if (task.getGetInfo() != null) {
					holder.setMalfunctionAdapter(R.id.childListView,
							task.getGetInfo(), type, position);
				} else {
					holder.setVisible(R.id.llMalfunctionItem, false);
				}
				holder.setOnClickListener(R.id.rlExtend, new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (v.getTag() == null) {
							holder.setVisible(R.id.childListView, true);
							v.setTag("extend");
						} else {
							holder.setVisible(R.id.childListView, false);
							v.setTag(null);
						}
					}
				});

				break;
			}
		}
	}

	/**
	 * @author: HYM
	 * @Title: doFinish
	 * @Description: TODO(完成报修) void
	 * @date: 2017-9-19
	 */
	void doFinish(String bid, String comments, int auditor_status,
			final int position, final int type) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("bid", bid);
		params.put("comments", comments);
		params.put("auditor_status", auditor_status + "");

		Log.e("dfs   ", params.toString());
		dialog = DialogTool.showDialog(dialog, getContext());
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_REPAIR_ALL_TEMP_FINISH, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								EventBus.getDefault().post(
										new RepairTaskListEvent(type, position,
												3));
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							DialogTool.hideDialog(dialog);
						}

					}

					@Override
					public void stringError(VolleyError error) {
						DialogTool.hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	void doFinishRepair(String bid, String comments, final int position,
			final int type) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("bid", bid);
		params.put("comments", comments);

		Log.e("dfs   ", params.toString());
		dialog = DialogTool.showDialog(dialog, getContext());
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_REPAIR_ALL_NORMAL_FINISH, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								EventBus.getDefault().post(
										new RepairTaskListEvent(type, position,
												4));
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							DialogTool.hideDialog(dialog);
						}

					}

					@Override
					public void stringError(VolleyError error) {
						DialogTool.hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("type", type + "");
		params.put("p", pageNo+ "");
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_REPAIR_ALL, "", params, new StringInterface(
						getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<RepairTask> temp = new Gson().fromJson(
										data,
										new TypeToken<List<RepairTask>>() {
										}.getType());
//								dataList.clear();
//								dataList.addAll(temp);
//								adapter.notifyDataSetChanged();
								if (isRefresh) {
									dataList.clear();
								}
								
								if (temp.size() > 0) {
									dataList.addAll(temp);
									pageNo++;
								}
								else {
									
								}
								
								adapter.notifyDataSetChanged();
								loadfinish = true; // 加载完成
								
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
	
	@Override
	public void onRefresh() {
		isRefresh = true;
		pageNo = 1;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}
	
	/**
	 * 处理中心
	 */
	Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_DATA:
				if (loadfinish) {
					loadfinish = false;
					getData();
				}
				break;
			default:
				break;
			}
		};
	};
	
	/**
	 * 作者：hym 日期：2017-4-6 描述：加载更多数据
	 */
	void loadMore() {
		isRefresh = false;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}
}
